# import numpy as np
# import torch
# import torchvision
# import torchvision.transforms as transforms
#
# mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=True,
#                                                 transform=transforms.ToTensor())
# mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=False, download=True,
#                                                transform=transforms.ToTensor())
# batch_size = 256
# num_workers = 4  # 多进程同时读取
# train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_workers)
# test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_workers)
#
# num_inputs = 784  # 图像是28 X 28的图像,共784个特征
# num_outputs = 10
#
# W = torch.tensor(np.random.normal(
#     0, 0.01, (num_inputs, num_outputs)), dtype=torch.float)
# b = torch.zeros(num_outputs, dtype=torch.float)
#
# W.requires_grad_(requires_grad=True)
# b.requires_grad_(requires_grad=True)
#
#
# def softmax(X):  # X.shape=[样本数,类别数]
#     X_exp = X.exp()
#     partion = X_exp.sum(dim=1, keepdim=True)  # 沿着列方向求和,即对每一行求和
#     # print(partion.shape)
#     return X_exp / partion  # 广播机制,partion被扩展成与Ｘ_exp同shape的,对应位置元素做除法
#
#
# def net(X):
#     # 通过`view`函数将每张原始图像改成长度为`num_inputs`的向量
#     return softmax(torch.mm(X.view(-1, num_inputs), W) + b)
#
#
# def cross_entropy(y_hat, y):
#     y_hat_prob = y_hat.gather(1, y.view(-1, 1))  # ,沿着列方向,即选取出每一行下标为y的元素
#     return -torch.log(y_hat_prob)
#
#
# def sgd(params, lr, batch_size):
#     for param in params:
#         param.data -= lr * param.grad / batch_size  # 注意这里更改param时用的param.data
#
#
# def evaluate_accuracy(data_iter, net):
#     acc_sum, n = 0.0, 0
#     for X, y in data_iter:
#         acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
#         n += y.shape[0]
#     return acc_sum / n
#
#
# num_epochs, lr = 5, 0.1
#
#
# def train():
#     for epoch in range(num_epochs):
#         train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
#         for X, y in train_iter:
#             # print(X.shape,y.shape)
#             y_hat = net(X)
#             l = cross_entropy(y_hat, y).sum()  # 求loss
#             l.backward()  # 反向传播,计算梯度
#             sgd([W, b], lr, batch_size)  # 根据梯度,更新参数
#
#             W.grad.data.zero_()  # 清空梯度
#             b.grad.data.zero_()
#
#             train_l_sum += l.item()
#             train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
#             n += y.shape[0]
#         test_acc = evaluate_accuracy(test_iter, net)
#         print('epoch %d, loss %.4f, train_acc %.3f，test_acc %.3f'
#               % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
#
#
# train()


import torch
import torchvision
import numpy as np
import sys
import random
import torchvision.transforms as transforms

sys.path.append('..')
batch_size = 256
mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', download=True, train=True,
                                                transform=transforms.ToTensor())
mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', download=True, train=False,
                                               transform=transforms.ToTensor())

if sys.platform.startswith('win'):
    num_worker = 0  # 表示不用额外的进程来加速读取数据

else:
    num_worker = 0
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_worker)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_worker)
num_inputs = 784
num_outputs = 10


def set_seed(seed=9699):  # seed的数值可以随意设置，本人不清楚有没有推荐数值
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    # 根据文档，torch.manual_seed(seed)应该已经为所有设备设置seed
    # 但是torch.cuda.manual_seed(seed)在没有gpu时也可调用，这样写没什么坏处
    torch.cuda.manual_seed(seed)
    # cuDNN在使用deterministic模式时（下面两行），可能会造成性能下降（取决于model）
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


set_seed(9699)  # 保证同一个随机种子产生的训练结果一致

W = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_outputs)), dtype=torch.float)
b = torch.zeros(num_outputs, dtype=torch.float)
# 同之前一样，我们需要模型参数梯度
W.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)

#实现sofimax运算
def softmax(X):
    X_exp = X.exp()
    partition = X_exp.sum(dim=1, keepdim=True)
    return X_exp / partition

#定义模型
def net(X):
    return softmax(torch.mm(X.view(-1, num_inputs), W) + b)

#手动实现交叉熵函数
def cross_entropy(y_hat, y):
    return - torch.log(y_hat.gather(1, y.view(-1, 1)))

#计算分类准确性
def accuracy(y_hat, y):
    return (y_hat.argmax(dim=1) == y).float().mean().item()


def evaluate_accuracy(data_iter, net):
    acc_sum, n = 0.0, 0
    for X, y in data_iter:
        acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
        n += y.shape[0]
    return acc_sum / n

#手动实现随机梯度下降
def sgd(params, lr, batch_size):
    for param in params:
        param.data -= lr * param.grad / batch_size


num_epochs, lr = 5, 0.1


def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
              params=None, lr=None, optimizer=None):
    for epoch in range(num_epochs):
        train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
        for X, y in train_iter:
            y_hat = net(X)
            l = loss(y_hat, y).sum()

            # 梯度清零
            if optimizer is not None:
                optimizer.zero_grad()
            elif params is not None and params[0].grad is not None:
                for param in params:
                    param.grad.data.zero_()

            l.backward()
            if optimizer is None:
                sgd(params, lr, batch_size)
            else:
                optimizer.step()  # “softmax回归的简洁实现”一节将用到

            train_l_sum += l.item()
            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
            n += y.shape[0]
        test_acc = evaluate_accuracy(test_iter, net)
        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
              % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))


train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, batch_size, [W, b], lr)
